package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.PageResult;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Daoying
 * creationTime: 2022/10/24 14:01
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    /*
     * 分页
     * */
    @PostMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult list = userService.findPage(queryPageBean);

        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, list);

    }

    /*
     * 查询所有的角色
     * */
    @GetMapping("/findAllRole")
    public Result findAllRole() {
        List<Role> list = userService.findAllRole();
        return new Result(true, MessageConstant.QUERY_ROLE_SUCCESS, list);
    }

    /*
     * 添加
     * */
    @PostMapping("/add")
    public Result add(@RequestBody User user, Integer[] roleIds) {
        userService.add(user, roleIds);
        return new Result(true, MessageConstant.ADD_USER_SUCCESS);
    }

    /*
     * 用户删除
     * */

    @GetMapping("/delete")
    public Result delete(int id) {
        userService.deleteById(id);
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
    }

    /*
     * 查询用户
     * */
    @GetMapping("/findById")
    public Result findById(int id) {
        User user = userService.findById(id);
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
    }

    /*
     * 通过用户id查询选中的角色id
     * */
    @GetMapping("/findRoelIdsByUserId")
    public Result findRoleIdByUserId(Integer userId) {
        List<Integer> list = userService.findRoleIdByUserId(userId);
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, list);
    }

    /**
     * 编辑用户
     */
    @PostMapping("/update")
    public Result update(@RequestBody User user, Integer[] roleIds) {
        userService.update(user, roleIds);
        return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
    }

    /**
     * 用户名回显
     */
    @GetMapping("/getUsername")
    public Result getUsername(){
        //获取登录用户的认证信息
        org.springframework.security.core.userdetails.User loginUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //登录用户名
        String username = loginUser.getUsername();
        //返回给前端
        return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,username);
    }


}
